package com.example.demo.controller;

import com.example.demo.Mapper.DocumentMapper;
import com.example.demo.context.BaseContext;
import com.example.demo.entity.Document;
import com.example.demo.result.Result;
import com.example.demo.util.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController("apiCommonController")
@RequestMapping("/api/common")
@Tag(name = "上传文件通用接口")
@Slf4j
@RequiredArgsConstructor
public class CommonController {
    @Resource
    private AliOssUtil aliOssUtil;

    private final DocumentMapper documentMapper;

    /**
     * 文件上传
     * @param file 传过来的文件
     * @return 文件的下载路径
     */
    @PostMapping("/upload")
    @Operation(summary = "知识库文档上传接口")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("上传文件：{}", file);
        //file.getBytes(),file对象转成的一个数组,objectName文件名通过uuid来生成
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            if(originalFilename==null){
                return Result.error("无效的文件名");
            }
            //截取元素文件名的后缀,dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //定义不允许上传的文件类型列表
            List<String> disAllowedExtension= Arrays.asList(".exe", ".dll", ".bat", ".sh", ".cmd", ".js", ".vbs");
            //检查文件名是否为不允许的类型
            if(disAllowedExtension.contains(extension)){
                return Result.error("禁止上传这种类型的文件");
            }
            //构造新的文件名称
            String objectName= UUID.randomUUID() +extension;
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            System.out.println("filePath: "+filePath);
            Document document=Document.builder()
                    .title(originalFilename)
                    .url(filePath)
                    .userId(BaseContext.getCurrentId())
                    .build();
            documentMapper.insert(document);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e);
        }

        return Result.error("上传失败");
    }
}

